//
//  UIImage+BZTheme.m
//  MZBasic
//
//  Created by Sings on 2022/8/22.
//

#import "UIImage+BZTheme.h"

@implementation UIImage (BZTheme)

+ (instancetype) BZTheme_imageNameWithKey:(NSString *) imageKey {
    NSString *name = BZThemeKeyToStr(imageKey);
    if (name == NULL) {
        name = @"";
    }
    NSInteger scale = [UIScreen mainScreen].scale;
    name = [name stringByReplacingOccurrencesOfString:@"@*x" withString:[NSString stringWithFormat:@"@%ldx",scale]];
    UIImage *image = [UIImage imageWithContentsOfFile:[BZThemeFilePath() stringByAppendingPathComponent:name]];
    if (image == nil) {
        image = [[UIImage alloc] init];
    }
    return image;
}

+ (instancetype) BZTheme_image:(NSString *) imagePath {
    SEL sel = NSSelectorFromString(imagePath);
    if ([[UIImage class] respondsToSelector:sel]) {
        return ((UIImage  * (*)(id, SEL))(void *) objc_msgSend)((id)[UIImage class], sel);
    }else {
        return [UIImage BZTheme_imageNameWithKey:imagePath];
    }
}

+ (UIImage*)gradientImageWithSize:(CGSize)size colors:(NSArray*)colors gradientType:(GradientDirection)gradientType {
    NSMutableArray *ar = [NSMutableArray arrayWithCapacity:colors.count];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint startPt = CGPointZero;
    CGPoint endPt = CGPointZero;
    
    switch (gradientType) {
        case GradientDirectionTopToBottom:
            startPt= CGPointMake(0.0, 0.0);
            endPt= CGPointMake(0.0, size.height);
            break;
        case GradientDirectionLeftToRight:
            startPt = CGPointMake(0.0, 0.0);
            endPt = CGPointMake(size.width, 0.0);
            break;
        case GradientDirectionBottomToTop:
            startPt = CGPointMake(0.0, size.height);
            endPt = CGPointMake(0.0, 0.0);
            break;
        case GradientDirectionRightToLeft:
            startPt = CGPointMake(size.width, 0.0);
            endPt = CGPointMake(0, 0.0);
            break;
    }
    CGContextDrawLinearGradient(context, gradient, startPt, endPt, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

@end
